package com.youbug.system.service.impl;

import cn.hutool.crypto.symmetric.AES;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.youbug.common.generator.MyVelocityTemplateEngine;
import com.youbug.system.entity.Generator;
import com.youbug.system.mapper.GeneratorMapper;
import com.youbug.system.service.IGeneratorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youbug.system.vo.GenerateInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.youbug.system.entity.Generator;
import org.springframework.util.ObjectUtils;
import com.youbug.common.vo.QueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.util.StringUtils;
import org.springframework.util.ObjectUtils;

import javax.sql.DataSource;

/**
 * <p>
 * VIEW 服务实现类
 * </p>
 *
 * @author youbug
 * @since 2023-12-27
 */
@Service
public class GeneratorServiceImpl extends ServiceImpl<GeneratorMapper, Generator> implements IGeneratorService {
        @Value("${spring.datasource.system.jdbc-url}")
        private String jdbcUrl;
        @Value("${spring.datasource.system.driver-class-name}")
        private String driverClassName;
        @Value("${spring.datasource.system.username}")
        private String username;
        @Value("${spring.datasource.system.password}")
        private String password;
        @Autowired
        private AES aes;

        @Override
        public IPage<Generator> getGeneratorPage(QueryVo<Generator> queryVo) {

        Page<Generator> paramPage = new Page<>();

        paramPage.setCurrent(queryVo.getCurrentPage());

        paramPage.setSize(queryVo.getPageSize());

        QueryWrapper<Generator> wrapper = new QueryWrapper<>();

        Generator generator = queryVo.getPayload();

        if(!ObjectUtils.isEmpty(generator)){
            if(StringUtils.hasText(generator.getTableName())){
                wrapper.eq("TABLE_NAME", generator.getTableName());
            }
            if(StringUtils.hasText(generator.getTableComment())){
                wrapper.eq("TABLE_COMMENT", generator.getTableComment());
            }
            if(!ObjectUtils.isEmpty(generator.getCreateTime())){
                wrapper.gt("create_time", generator.getCreateTime());
            }
        }
        if(!ObjectUtils.isEmpty(queryVo.getStartTime())){
            wrapper.gt("create_time", queryVo.getStartTime());
        }
        if(!ObjectUtils.isEmpty(queryVo.getEndTime())){
            wrapper.lt("create_time", queryVo.getEndTime());
        }
        wrapper.orderByDesc("create_time");

        Page<Generator> page = this.page(paramPage, wrapper);

        return page;
        }

    @Override
    public boolean generate(GenerateInfo generateInfo) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("youbug");
        gc.setOpen(false);
        gc.setSwagger2(true); // 实体属性 Swagger2 注解
        gc.setFileOverride(generateInfo.isFileOverride());//重复执行覆盖原文件
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(jdbcUrl);
        // dsc.setSchemaName("public");
        dsc.setDriverName(driverClassName);
        dsc.setUsername(username);
        dsc.setPassword(aes.decryptStr(password));
        mpg.setDataSource(dsc);
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(generateInfo.getModuleName());
        pc.setParent("com.youbug");
        mpg.setPackageInfo(pc);
        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {

            }
        };

        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        // 配置自定义输出模板
        //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
//         templateConfig.setEntity("templates/entity2.java");
//         templateConfig.setService("templates/entity2.java");
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);

        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类
//        strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // 写于父类中的公共字段
        strategy.setSuperEntityClass("com.youbug.common.config.BaseEntity");
        strategy.setSuperEntityColumns("create_user","create_time","update_user","update_time");
        strategy.setInclude(generateInfo.getTableName());//表名，号分割
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new MyVelocityTemplateEngine());
        mpg.execute();

        return true;
    }

}
